package red.mlz.app.controller.sms;


import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import red.mlz.module.module.sms.service.SmsService;
import red.mlz.module.utils.Response;

import java.util.Random;
import java.util.concurrent.*;

@RestController
@Slf4j
public class SmsController {

    @Autowired
    private SmsService smsService;

    private final ExecutorService executor = new ThreadPoolExecutor(
            4, 4,
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(1000),  // 有界队列（容量1000）
            new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName("sms-" + thread.getId());
                    return thread;
                }
            },
            new ThreadPoolExecutor.AbortPolicy()  // 队列满时抛出RejectedExecutionException
    );

    /**
     * 同步发送短信
     *
     * @return
     */
    @RequestMapping("/sms/sync")
    public Response syncSend(@RequestParam(name = "phone") String phone) {
        try {
            Random random = new Random();
            int random4Digit = random.nextInt(9000) + 1000; // 1000-9999
            String content = String.valueOf(random4Digit);
            smsService.syncSend(phone, content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new Response(1001);
    }

    /**
     * 多线程发送短信
     *
     * @return
     */
    @RequestMapping("/sms/batch")
    public Response batchSend(@RequestParam(name = "phones") String phones) {
        try {
            String[] phoneList = phones.split(",");
            for (String phone : phoneList) {
                executor.submit(() -> {
                    Random random = new Random();
                    int random4Digit = random.nextInt(9000) + 1000; // 1000-9999
                    String content = String.valueOf(random4Digit);
                    smsService.syncSend(phone, content);
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new Response(1001);
    }

    /**
     * 异步发送短信调用定时任务
     * {@link red.mlz.app.crond.SmsSendCrond#doSendSms()}
     * @return
     */
    @RequestMapping("/sms/async")
    public Response asyncSend(@RequestParam(name = "phone") String phone) {
        try {
            Random random = new Random();
            int random4Digit = random.nextInt(9000) + 1000; // 1000-9999
            String content = String.valueOf(random4Digit);
            smsService.asyncSend(phone, content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new Response(1001);
    }

}
